#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
语音助手WebSocket版本演示
"""

import json
import os
import logging
from voice_assistant import VoiceAssistant

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def run_websocket_demo():
    print("=== 语音助手WebSocket版本演示 ===")
    print("本演示将展示以下功能:")
    print("1. 音频文件处理（语音转文本 + 文本转回答）")
    print("2. 直接文本对话")
    print("3. 文本转语音合成")
    print("4. 完整音频到音频流程")
    print("5. 对话历史管理")

    assistant = VoiceAssistant()

    # --- 1. 音频文件处理演示 ---
    print("\n=== 音频处理演示 ===")
    audio_file = "test_1.pcm"
    if not os.path.exists(audio_file):
        print(f"错误: 未找到音频文件 '{audio_file}'。请确保文件存在。")
        return

    file_size = os.path.getsize(audio_file)
    # 假设16kHz, 16bit, 单声道PCM，每秒32000字节
    duration_seconds = round(file_size / (16000 * 2), 2)

    print(f"【音频文件信息】")
    print(f"文件: {audio_file}")
    print(f"大小: {file_size} 字节")
    print(f"时长: {duration_seconds} 秒")

    print("\n【开始处理音频文件】")
    print("==================================================")
    try:
        transcribed_text, ai_response = assistant.process_audio_file(audio_file)
        print("==================================================")
        print(f"\n【转写结果】")
        print(f"用户: {transcribed_text}")
        print(f"\n【AI回答】")
        print(f"助手: {ai_response}")
    except Exception as e:
        print(f"音频处理失败: {e}")

    # --- 2. 文本对话演示 ---
    print("\n=== 文本对话演示 ===")
    test_conversations = [
        "你好，请介绍一下你自己",
        "请解释一下什么是机器学习",
        "推荐一本编程书籍"
    ]

    for i, text_input in enumerate(test_conversations):
        print(f"\n【对话 {i+1}】")
        print(f"用户: {text_input}")
        try:
            response = assistant.process_text_input(text_input, stream=False)
            print(f"助手: {response}")
        except Exception as e:
            print(f"对话失败: {e}")

    # --- 3. 文本转语音合成演示 ---
    print("\n=== 文本转语音合成演示 ===")
    test_text = "你好，这是语音合成测试"
    print(f"要合成的文本: {test_text}")
    
    try:
        audio_file = assistant.synthesize_text(test_text, "test_synthesis.pcm")
        if audio_file:
            file_size = os.path.getsize(audio_file)
            print(f"语音合成成功，文件: {audio_file}")
            print(f"文件大小: {file_size} 字节")
        else:
            print("语音合成失败")
    except Exception as e:
        print(f"语音合成失败: {e}")

    # --- 4. 完整音频到音频流程演示 ---
    print("\n=== 完整音频到音频流程演示 ===")
    try:
        input_audio = "test_1.pcm"
        output_audio = "complete_flow_output.pcm"
        
        print(f"输入音频: {input_audio}")
        print(f"输出音频: {output_audio}")
        
        # 处理音频文件
        transcribed_text, ai_response = assistant.process_audio_file(input_audio)
        
        # 合成AI回答的语音
        if ai_response:
            synthesized_audio = assistant.synthesize_text(ai_response, output_audio)
            if synthesized_audio:
                file_size = os.path.getsize(synthesized_audio)
                print(f"完整流程成功！")
                print(f"转写文本: {transcribed_text}")
                print(f"AI回答: {ai_response}")
                print(f"合成音频: {synthesized_audio} ({file_size} 字节)")
            else:
                print("语音合成失败")
        else:
            print("AI回答为空，无法合成语音")
            
    except Exception as e:
        print(f"完整流程失败: {e}")

    # --- 5. 对话历史 ---
    print("\n--- 对话历史 ---")
    try:
        history = assistant.get_conversation_history()
        if not history:
            print("暂无对话历史")
        else:
            for i, msg in enumerate(history):
                role = "用户" if msg["role"] == "user" else "助手"
                content = msg["content"][:50] + "..." if len(msg["content"]) > 50 else msg["content"]
                print(f"{i+1}. {role}: {content}")
    except Exception as e:
        print(f"获取对话历史失败: {e}")

    print("\n=== 演示完成 ===")
    print("语音助手WebSocket版本演示已成功运行！")

if __name__ == "__main__":
    run_websocket_demo()
